package com.he.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.he.baseservice.exceptionhandler.EduException;
import com.he.commonutils.R;
import com.he.eduservice.client.VodClient;
import com.he.eduservice.entity.EduVideo;
import com.he.eduservice.entity.VideoInfoForm;
import com.he.eduservice.mapper.EduVideoMapper;
import com.he.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author testhejinyu
 * @since 2021-06-02
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    @Autowired
    private VodClient vodClient;

    @Override
    public void addVideo(VideoInfoForm videoInfoForm) {

        EduVideo eduVideo = new EduVideo();

        BeanUtils.copyProperties(videoInfoForm,eduVideo);

        int insert = baseMapper.insert(eduVideo);
        if(insert == 0){
            throw new EduException(20001,"添加小节失败！");
        }
    }

    @Override
    public EduVideo findVideoById(String id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id",id);
        EduVideo eduVideo = baseMapper.selectOne(queryWrapper);
        return eduVideo;
    }

    @Override
    public void updateVideo(VideoInfoForm videoInfoForm) {

        EduVideo eduVideo = new EduVideo();

        BeanUtils.copyProperties(videoInfoForm,eduVideo);

        int update = baseMapper.updateById(eduVideo);

        if(update == 0){
            throw new EduException(20001,"修改小节失败！");
        }
    }

    @Override
    public void deleteVideo(String id) {
        //先查询小节的视频资源

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id",id);

        // 查询云端视频id
        EduVideo eduVideo = baseMapper.selectOne(queryWrapper);
        String videoSourceId = eduVideo.getVideoSourceId();
        if(!StringUtils.isEmpty(videoSourceId)){
            R removeVideo = vodClient.removeVideo(videoSourceId);
            System.out.println(removeVideo);
        }

        int delete = baseMapper.delete(queryWrapper);
        if(delete == 0){
            throw new EduException(20001,"删除小节失败！");
        }
    }
}
